package net.kunyv.base.shiro;

import net.kunyv.base.entity.SysUser;
import net.kunyv.base.service.SysUserService;
import net.kunyv.util.HdUtil;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author sunyb
 * @create 2017-03-02 16:18
 */
public class RememberAuthenticationFilter extends FormAuthenticationFilter {
    @Resource
    private SysUserService sysUserService;

    /**
     * 这个方法决定了是否能让用户登录
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);

        //如果 isAuthenticated 为 false 证明不是登录过的，同时 isRememberd 为true 证明是没登陆直接通过记住我功能进来的
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            if(HdUtil.getLoginUser()==null){
                String username = subject.getPrincipal().toString();
                SysUser sysUser = sysUserService.getUserByUserName(username);
                UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getPassword(), true);
                subject.login(token);
            }
            return true;
        } else {
            return subject.isAuthenticated() || subject.isRemembered();
        }

    }
}
